package com.example.cc.client.utils;

import cn.hutool.core.util.StrUtil;
import lombok.experimental.UtilityClass;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 配置工具类
 */
@UtilityClass
@SuppressWarnings("all")
public class ConfigUtil {

    public static final String DATE_FORMAT = "yyyy-MM-dd";

    //获得原始的key
    public String getOriginalKey(String key) {
        if (StrUtil.isBlank(key) || !key.contains("${")) {
            return key;
        }
        return key.replace("${", "").replace("}", "");
    }

    public static <T> T convertValue(Object value, Class<T> targetType) {
        if (value == null || targetType.isInstance(value)) {
            return (T) value;
        }
        if (targetType.equals(String.class)) {
            return (T) value.toString();
        } else if (targetType.equals(Integer.class) || targetType.equals(int.class)) {
            return (T) Integer.valueOf(value.toString());
        } else if (targetType.equals(Long.class) || targetType.equals(long.class)) {
            return (T) Long.valueOf(value.toString());
        } else if (targetType.equals(Double.class) || targetType.equals(double.class)) {
            return (T) Double.valueOf(value.toString());
        } else if (targetType.equals(Float.class) || targetType.equals(float.class)) {
            return (T) Float.valueOf(value.toString());
        } else if (targetType.equals(Boolean.class) || targetType.equals(boolean.class)) {
            return (T) Boolean.valueOf(value.toString());
        } else if (targetType.equals(Date.class)) {
            SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT);
            try {
                return (T) dateFormat.parse(value.toString());
            } catch (ParseException e) {
                throw new IllegalArgumentException("Cannot parse date: " + value);
            }
        } else {
            throw new IllegalArgumentException("Unsupported target type: " + targetType);
        }
    }
}
